package com.example.seckill.domain.model;

import com.example.seckill.applicatoin.exception.ResultCodeMapper;
import com.example.seckill.applicatoin.exception.SystemException;
import com.example.seckill.domain.share.DddEntity;
import lombok.*;
import org.hibernate.Hibernate;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author Martin
 */
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Table
@Entity
public class Product implements DddEntity<Product> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    private Integer originStock;
    private Integer stockAvailable;
    private BigDecimal price;
    private String description;

    public Product(Long id, String name, Integer stockAvailable, BigDecimal price, String description) {
        this.id = id;
        this.name = name;
        this.originStock = stockAvailable;
        this.stockAvailable = stockAvailable;
        this.price = price;
        this.description = description;
    }


    // getters and setters
    // ...

    public void reduceStockQuantity(Integer quantity) {
        if (quantity > stockAvailable) {
            throw new IllegalArgumentException("Stock quantity is not enough.");
        }
        stockAvailable -= quantity;
    }

    public void increaseStockQuantity(Integer quantity) {
        stockAvailable += quantity;
    }

    public void reduceStock(Integer quantity){
        if(stockAvailable - quantity < 0){
            throw new SystemException("库存不足", ResultCodeMapper.STOCK_ERROR);
        }
        stockAvailable -= quantity;
    }

    @Override
    public boolean sameIdentityAs(Product other) {
        return other != null && other.getId().equals(this.id);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
        Product product = (Product) o;
        return id != null && Objects.equals(id, product.id);
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }
}
